// pages/electronic-invoice/electronic-invoice.js
Page({
	data: {
		currentPatient: {
			name: '',
			relationship: '本人',
			cardNumber: ''
		},
		patientList: [],
		showPatientModal: false
	},

	onLoad(options) {
		console.log('电子发票页面加载')
		this.loadPatientInfo()
	},

	// 加载就诊人信息
	loadPatientInfo() {
		wx.request({
			url: 'http://localhost:8005/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				if (res.statusCode === 200 && res.data) {
					let list = res.data
					if (typeof list === 'string') {
						try { list = JSON.parse(list) } catch (e) { return }
					}
					if (list.code !== undefined) list = list.data
					if (!Array.isArray(list)) return
					
					// 保存完整的就诊人列表
					const mapped = list.map(p => ({
						id: p.id,
						name: p.name,
						relationship: p.relationTypeName || '本人',
						cardNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
					}))
					
					this.setData({ patientList: mapped })
					
					// 找到默认就诊人
					const defaultPatient = list.find(p => p.isDefault === 1)
					if (defaultPatient) {
						this.setData({
							currentPatient: {
								name: defaultPatient.name,
								relationship: defaultPatient.relationTypeName || '本人',
								cardNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
							}
						})
					} else {
						// 如果没有默认就诊人，使用第一个就诊人
						const firstPatient = list[0]
						if (firstPatient) {
							this.setData({
								currentPatient: {
									name: firstPatient.name,
									relationship: firstPatient.relationTypeName || '本人',
									cardNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
								}
							})
						}
					}
				}
			}
		})
	},

	// 显示切换就诊人弹窗
	showPatientSelector() {
		console.log('显示切换就诊人弹窗')
		this.setData({
			showPatientModal: true
		})
	},

	// 隐藏切换就诊人弹窗
	hidePatientSelector() {
		console.log('隐藏切换就诊人弹窗')
		this.setData({
			showPatientModal: false
		})
	},

	// 阻止事件冒泡
	stopPropagation() {
		// 阻止事件冒泡
	},

	// 选择就诊人
	selectPatient(e) {
		const patient = e.currentTarget.dataset.patient
		console.log('选择就诊人:', patient)
		
		this.setData({
			currentPatient: patient,
			showPatientModal: false
		})

		// 保存到本地存储
		const cacheUser = wx.getStorageSync('userInfo') || {}
		wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
	},

	// 选择发票类型
	selectInvoiceType(e) {
		const type = e.currentTarget.dataset.type
		console.log('选择发票类型:', type)
		
		if (type === 'pending') {
			wx.navigateTo({
				url: '/pages/pending-invoice/pending-invoice'
			})
			} else if (type === 'issued') {
		wx.navigateTo({
			url: '/pages/issued-invoice/issued-invoice'
		})
	}
	}
})
